<!--
 * @Descripttion: 批次管理-新建/编辑
 * @Author: 何伟伦 weilun@ssc-hn.com
 * @Date: 2024-04-10
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-04-25
-->
<script lang="ts" setup>
  import { ArrowLeftOutlined } from '@ant-design/icons-vue'
  import { message } from 'ant-design-vue'
  import { onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { requestAddBatch, requestCreateBatchNumber, requestGetBatchDetail, requestGetBatchGoodsList, requestUpdateBatch } from '/@/api/business/tracecode/batch'
  import { requestGetContentList } from '/@/api/content/contentInfo'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const router = useRouter()
  const route = useRoute()
  const { batchId } = route.query

  const loading = ref<boolean>(false)
  const formRef = ref()
  const goodsData = ref<GetAllGoodsTypes.IResponse[]>([])
  const questionData = ref<GetContentListTypes.IResponse[]>([])
  const formState = ref<any>({
    batchName: null,
    batchNumber: null,
    notes: null,
    goodId: null,
    questionnaireId: null,
    quantity: null,
  })

  const rules = {
    batchName: [{ required: true, message: '请输入批次名称' }],
    batchNumber: [{ required: true, message: '未生成批次编号' }],
    goodId: [{ required: true, message: '请选择关联商品' }],
    questionnaireId: [{ required: true, message: '请选择关联问卷' }],
    quantity: [{ required: true, message: '请输入数量' }],
  }
  /**
   * 回退页面
   */
  const pageBack = () => {
    router.replace({
      path: '/code/batchManage/list',
    })
  }
  /**
   * 获取批次详情（编辑）
   */
  const getDetail = async () => {
    loading.value = true
    const { responseCode, responseData } = await requestGetBatchDetail({
      batchId: batchId as string,
    })
    loading.value = false
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const { batchName, batchNumber, notes, goodId, questionnaireId, quantity } = responseData
      formState.value.batchName = batchName
      formState.value.batchNumber = batchNumber
      formState.value.notes = notes
      formState.value.goodId = goodId
      formState.value.questionnaireId = questionnaireId
      formState.value.quantity = quantity
    }
  }

  /**
   * 初始化商品列表
   */
  const initGoodsList = async () => {
    const { responseCode, responseData } = await requestGetBatchGoodsList({})
    if (responseCode === HttpCodeEnum.SUCCESS) {
      goodsData.value = responseData
    }
  }

  /**
   * 初始化问卷列表
   */
  const initQuestionList = async () => {
    const { responseCode, responseData } = await requestGetContentList({})
    if (responseCode === HttpCodeEnum.SUCCESS) questionData.value = responseData
  }

  /**
   * 新建生成批次号
   */
  const initBatchNumber = async () => {
    const { responseCode, responseData } = await requestCreateBatchNumber({})
    if (responseCode === HttpCodeEnum.SUCCESS) formState.value.batchNumber = responseData
  }

  /**
   * 保存
   */
  const submit = async () => {
    formRef.value.validate().then(async () => {
      loading.value = true
      const action = batchId ? requestUpdateBatch({ ...formState.value, batchId }) : requestAddBatch({ ...formState.value })
      const { responseCode } = await action
      loading.value = false
      if (responseCode === HttpCodeEnum.SUCCESS) {
        message.success(`${batchId ? '编辑' : '新增'}批次成功`)
        router.back()
      }
    })
  }
  onMounted(() => {
    initGoodsList()
    initQuestionList()
    if (batchId) {
      getDetail()
    } else {
      initBatchNumber()
    }
  })
</script>

<template>
  <div class="product-edit-add">
    <div class="product-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="pageBack()" />
      <span>{{ batchId ? '编辑' : '新增' }}批次</span>
    </div>
    <a-divider />
    <div class="product-form-box">
      <a-form :model="formState" :colon="false" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" :rules="rules" ref="formRef" name="add_form" labelAlign="right">
        <a-form-item label="批次名称" name="batchName">
          <a-input v-model:value="formState.batchName" allow-clear />
        </a-form-item>
        <a-form-item label="批次编号" name="batchNumber">
          <a-input v-model:value="formState.batchNumber" disabled />
        </a-form-item>
        <a-form-item label="关联商品" name="goodId">
          <a-select v-model:value="formState.goodId" placeholder="请选择商品" :disabled="batchId">
            <a-select-option v-for="item in goodsData" :key="item.goodId" :value="item.goodId">{{ item.goodsName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联问卷" name="questionnaireId">
          <a-select v-model:value="formState.questionnaireId" placeholder="请选择问卷" :disabled="batchId">
            <a-select-option v-for="item in questionData" :key="item.contentId" :value="item.contentId">{{ item.contentTitle }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数量" name="quantity">
          <a-input-number style="width: 100%" v-model:value="formState.quantity" :disabled="batchId" :precision="0" :min="1" :max="99999" :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
        </a-form-item>
        <a-form-item label="备注" name="notes">
          <a-textarea :rows="4" v-model:value="formState.notes" allow-clear showCount :maxlength="200" />
        </a-form-item>
        <a-form-item label=" ">
          <a-button type="primary" @click="submit" :loading="loading">保存</a-button>
          <a-button style="margin-left: 10px" @click="router.back()" :loading="loading">取消</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .product-edit-add {
    background: #fff;
    padding-bottom: 32px;

    .product-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
      padding: 22px 0 0 26px;
    }

    .product-form-box {
      width: 80%;
      margin: 24px auto;
    }
  }
</style>
